﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc;
using WorkFlowCore.Authorization;
using WorkFlowCore.Authorization.JWT;
using WorkFlowCore.Framework.Migrations;
using WorkFlowCore.Common.Tracers;
using WorkFlowCore.Framework.UserSelectors;
using WorkFlowCore.Host.ViewModels.Account;
using WorkFlowCore.IRepositories;
using WorkFlowCore.Workflows;
using Microsoft.AspNetCore.Http;
using WorkFlowCore.Common.Authorization.JWT;

namespace WorkFlowCore.Host.Controllers
{
    /// <summary>
    /// 账号管理
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class AccountController : AbpControllerBase
    {
        private readonly JWTAuthenticationManager authenticationManager;
        private readonly IWorkflowSession workflowSession;
        private readonly IWorkflowRepository workflowRepository;
        private readonly IHttpContextAccessor httpContextAccessor;

        public AccountController(JWTAuthenticationManager authenticationManager,
            IWorkflowSession workflowSession,
            IWorkflowRepository workflowRepository,
            IHttpContextAccessor httpContextAccessor)
        {
            this.authenticationManager = authenticationManager;
            this.workflowSession = workflowSession;
            this.workflowRepository = workflowRepository;
            this.httpContextAccessor = httpContextAccessor;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost("Login")]
        [AllowAnonymous]
        public LoginOutput Login([FromBody] LoginInput input)
        {
            var staticUer = UserList.Users.FirstOrDefault(u => u.Id == input.uid);
            var localPwd = JWTAuthenticationManager.GetLocalPwd();
            if (staticUer != null && input.pwd.Equals(JWTAuthenticationOptions.DefaultPwd))
            {
                var user = new Common.Authorization.JWT.AuthorizationUser { Id = staticUer.Id, Name = staticUer.Name, IsManager = false,AppId = input.appId??"" };
                return new LoginOutput
                {
                    token = authenticationManager.Login(user, null),
                    userInfo = user,
                };
            }
            else
            {

                var inputPwd = JWTAuthenticationManager.PwdEncrypt(input.uid + input.pwd);
                if (!localPwd.Equals(inputPwd))
                {
                    throw new Exception("验证失败");
                }
                var user = new Common.Authorization.JWT.AuthorizationUser { Id = input.uid, Name = input.uid, IsManager = true, AppId = input.appId ?? "" };
                return new LoginOutput
                {
                    token = authenticationManager.Login(user, null),
                    userInfo = user,
                };
            }


        }

        /// <summary>
        /// 退出登录 
        /// </summary>
        [HttpPost("Logout")]
        [AllowAnonymous]
        public void Logout()
        {
            authenticationManager.Logout(workflowSession?.User?.Id);
        }

        /// <summary>
        /// 获取所有用户（仅模拟用户）
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAllList")]
        [AllowAnonymous]
        public async Task<List<UserSelectors.User>> GetAllList()
        {
            return  await Task.FromResult(UserList.Users.Select(u => new UserSelectors.User { Id = u.Id, Name = u.Name }).ToList());
        }

        /// <summary>
        /// 自动 登录
        /// 用于第三方平台跳转引擎工作台。
        /// 通常需要通过 header 传递来自第三方平台的 token （或其他标识），具体key名以认证插件的为准。
        /// 比如 采用默认身份认证插件 DefaultCustomizationVerifyExtension 时，通过 ThirdpartAuthorization 传递 第三方平台的认证信息。
        /// 
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost("AutoLogin")]
        [HttpGet("AutoLogin")]
        [AllowAnonymous]
        public LoginOutput AutoLogin()
        {
            var context = httpContextAccessor.HttpContext;
            var pluginid = context.GetContextParameter("pluginid");
            var appid = context.GetContextParameter("appid");
            var accessToken = context.GetContextParameter("access_token");//eyAgIm5hbWUiOiAiYWRtaW4iLCAgImlkIjogImFkbWluIiwgICJpc01hbmFnZXIiOiB0cnVlLCAgImFwcElkIjogIiJ9
            var thirdpartauthorization = context.GetContextParameter("thirdpartauthorization");

            var validOutput = authenticationManager.CheckCustomizationVerify(new VerifyInput { Context = context, AccessToken = accessToken, AppId = appid, ThirdPartToken = thirdpartauthorization }, pluginid);

            if (validOutput?.IsValid ?? false)
            {
                accessToken = authenticationManager.Login(validOutput.User, validOutput.Claims);
            }
            else
            {
                throw new Exception("验证失败");
            }

            var user = new Common.Authorization.JWT.AuthorizationUser
            {
                Id = validOutput?.User?.Id,
                Name = validOutput?.User?.Name,
                IsManager = validOutput?.User?.IsManager ?? false,
                AppId = appid
            };
            return new LoginOutput
            {
                token = authenticationManager.Login(user, null),
                userInfo = user,
            };
        }
        /// <summary>
        /// 获取用户信息
        /// 登录后需重新获取用户信息时，可用该接口。
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetUserInfo")]
        public async Task<Common.Authorization.JWT.AuthorizationUser> GetUserInfo()
        {
            var result =  new Common.Authorization.JWT.AuthorizationUser()
            {
                Id = workflowSession?.User?.Id,
                Name = workflowSession?.User?.Name,
                IsManager = workflowSession?.User?.IsManager ?? false,
                AppId = workflowSession?.User?.AppId
            };
            return await Task.FromResult(result);
        }
        /// <summary>
        /// 获取所有的appid
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAllAppIds")]
        [AllowAnonymous]
        public async Task<List<string>> GetAllAppIds()
        {
            using (var activity = WorkflowActivitySource.Source?.StartActivity("GetAllAppIds"))
            {
                return await workflowRepository.GetAllExistsAppIds();
            } ;
            
        }
    }
}
